#include "TetGen.hpp"
#include "PolyMesh.hpp"

#include "SmeshFile.hpp"
#include "TetGenSource.hpp"
void TetGen::Tetrahedralize(const Mesh& aMesh,
                            PolyMesh&   aPolyMesh)
{
   aPolyMesh.Clear();
   char tmpFileBaseName[] = "tmpsmesh";
   char tmpFileName[] = "tmpsmesh.smesh";
   SmeshFile::Write(tmpFileName, aMesh);
   tetgenio in;
   tetgenio out;
   in.load_poly(tmpFileBaseName);
   try
   {
      tetrahedralize("pA", &in, &out, 0, 0);
   }
   catch (...)
   {
      return;
   }
   aPolyMesh.verts.resize(out.numberofpoints);
   for (int i = 0; i < out.numberofpoints; ++i)
   {
      Vec3& v = aPolyMesh.verts[i];
      int ind = i*3;
      v[0] = (float)out.pointlist[ind++];
      v[1] = (float)out.pointlist[ind++];
      v[2] = (float)out.pointlist[ind++];
   }

   for (int i = 0; i < out.numberoftetrahedra; ++i)
   {
      int ind = i * 4;
      Polyhedron poly;
      poly.vertex[0] = out.tetrahedronlist[ind++]-1;
      poly.vertex[1] = out.tetrahedronlist[ind++]-1;
      poly.vertex[2] = out.tetrahedronlist[ind++]-1;
      poly.vertex[3] = out.tetrahedronlist[ind++]-1;
      poly.arity = 4;
      poly.material = (int)out.tetrahedronattributelist[i];
      aPolyMesh.polys.push_back(poly);
   }
   aPolyMesh.Recompute();
}
